//
//  SinaUserAccountViewModel.swift
//  MySinaWeiBoSwiftProject
//
//  Created by apple on 2016/11/15.
//  Copyright © 2016年 WangChen. All rights reserved.
//

/*
 1.封装数据逻辑处理
 2.封装网络请求
 3.封装数据缓存
 */


import UIKit
import SVProgressHUD

class SinaUserAccountViewModel: NSObject {

    //全局只有一个用户 单例
    static let shared: SinaUserAccountViewModel = SinaUserAccountViewModel()
    
    //引入model
    var userAccount: SinaUserAccount?
    
    
    //用户头像
    var avatarLargeURL: URL?{
        
        if let urlstr = userAccount?.avatar_large {
            return URL(string: urlstr)!
        }
        return nil
    }
    
    
    //增加一个属性,判断用户是否登录
    var userLogin: Bool{
    
        if userAccount?.access_token != nil && !isExperis{
            return true
        }
        return false
    }
    //判断令牌是否过期
    var isExperis: Bool{
        
        if userAccount?.expires_date?.compare(Date()) ==  ComparisonResult.orderedDescending{
            return false
        }
        return true
        
    }
    
    
    // MARK:
    // MARK: - 重写一个构造函数,在一开始就给userAccount赋值
    override init() {
        super.init()
        userAccount = loadUserAccount()
    }
    
    
    
    // MARK:
    // MARK: - 访问token
    func accessToken(code: String,finished: @escaping (Bool)->()) {
        //利用自己封装的AFN来访问token
        let parameter = ["client_id":appKey,
                         "client_secret":appSecret,
                         "grant_type":"authorization_code",
                         "code":code,
                         "redirect_uri":redirectUrl]
        
        MyHTTPTools.sharedTool.request(requestMethod: .POST, urlStr: tokenUrlStr, paramters: parameter, finish: { (responseObj, error) in
            
            if error != nil {
                //视图操作放到controller中回调
//                SVProgressHUD.showError(withStatus: "世界上最远的距离就是没有网络..")
                finished(false)
                return
            }
            print("请求成功")
            
            //获取用户信息
            self.accessUserInfo(dict: responseObj as! [String : Any], accessFinished: finished)
            
        })
        
        
    }
    
    // MARK:
    // MARK: - 获取用户信息
    private func accessUserInfo(dict: [String : Any], accessFinished: @escaping (Bool)->()){
        
        let access_token = dict["access_token"]
        let uid = dict["uid"]
        
        let parameter = ["access_token":access_token,
                         "uid":uid]
        
        MyHTTPTools.sharedTool.request(requestMethod: .GET, urlStr: userShowUrlStr, paramters: parameter, finish: { (responseObj,error) -> () in
            
            if error != nil{
                //视图操作放到controller中回调
//                SVProgressHUD.showError(withStatus: "世界上最远的距离就是没有他妈的网络")
                accessFinished(false)
                return
            }
            
            var userInfoDict = responseObj as! [String: Any]
            
            //把usertoken的信息集成进来
            for (key,value) in dict{
                userInfoDict[key] = value
            }
            
            //转化成模型
            let userAccount = SinaUserAccount.init(dict: userInfoDict)
            
            //存入沙盒
            self.saveUserAccount(userAccount: userAccount)
            
            //给userAccount赋值
            self.userAccount = userAccount
            
            //成功回调
            accessFinished(true)
            
        })
        
    }
    
    
    
    // MARK:
    // MARK: - 归档 存储模型对象到沙盒Document
    private func saveUserAccount(userAccount: SinaUserAccount) {
        print(accountPath)
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
    }
    
    
    // MARK:
    // MARK: - 解档 从沙盒读取数据
    private func loadUserAccount() -> SinaUserAccount?{
        
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath)
        if let userinfo = userAccount as? SinaUserAccount{
            return userinfo
        }
        return nil
    }
    
    
    
    
    
    
    
}
